package org.ws.lifebacklog.activity;

import org.ws.lifebacklog.LifeBacklogApp;
import org.ws.lifebacklog.R;
import org.ws.lifebacklog.event.GenericBroadcastReceiver;
import org.ws.lifebacklog.event.GenericEvent;
import org.ws.lifebacklog.event.LocaleChangedEvent;
import org.ws.lifebacklog.util.AppConfig;
import org.ws.lifebacklog.util.Callback;
import org.ws.lifebacklog.util.Logger;
import org.ws.lifebacklog.view.NavigationBarView;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

public class GenericActivity extends Activity {

	public static final String EVENT_LOCALE_CHANGED = "event-locale-changed";
	public static final String RESULT_CODE = "result-code";
	public static final String RESULT_DATA = "result-data";

	protected ClickListener onClickListener = new ClickListener();
	private NavigationBarView navigationBar;
	private AppConfig conf;

	private GenericBroadcastReceiver receiver = new GenericBroadcastReceiver();

	private boolean needRestarthActivity;

	protected OnClickListener defaultFinishEvent = new OnClickListener() {

		@Override
		public void onClick(View v) {
			finish();
		}
	};

	protected void registerEvent(String action, GenericEvent event) {
		receiver.addEventListener(action, event);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Logger.d(getClass(), "created!");
		registerReceiver(receiver, GenericEvent.getDefaultIntentFilter());
		registerEvent(LocaleChangedEvent.EVENT_TYPE, new GenericEvent() {

			@Override
			public void execute() {
				Logger.d(getClass(), "Locale changed");
				needRestarthActivity = true;
			}
		});
		refresh();
	}

	public void startActivityForResult(Intent intent, int requestCode, Callback callback) {
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		if (getParent() instanceof GroupBaseActivity) {
			((GroupBaseActivity) getParent()).startActivityForResult(intent, requestCode, callback);
		} else {
			startActivityForResult(intent, requestCode);
		}
	}

	public void startActivity(Intent intent, Callback callback) {
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		if (getParent() instanceof GroupBaseActivity) {
			((GroupBaseActivity) getParent()).startActivity(intent, callback);
		} else {
			startActivity(intent);
		}
	}

	public void refresh() {

	}

	/** {@inheritDoc} */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		handleResults(requestCode, resultCode, data);
	}

	protected void handleResults(int requestCode, int resultCode, Intent data) {
	}

	/**
	 * @return the navigationBar
	 */
	public final NavigationBarView getNavigationBar() {
		if (navigationBar == null && findViewById(R.id.navigation_bar) != null) {
			navigationBar = (NavigationBarView) findViewById(R.id.navigation_bar);
		}
		return navigationBar;
	}

	public void initNavBar(CharSequence title, Integer backTitleId, OnClickListener backEvent, Integer rightButtonName,
			OnClickListener nextEvent) {
		if (getNavigationBar() != null) {
			getNavigationBar().update(title, backTitleId, backEvent, rightButtonName, nextEvent);
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		Logger.d(getClass(), "destroyed");
		unregisterReceiver(receiver);
	}

	public void restart() {
		onDestroy();
		onCreate(getWindow().saveHierarchyState());
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (needRestarthActivity) {
			restart();
			needRestarthActivity = false;
		} else {
			refresh();
		}

	}

	protected void startActivity(Class<? extends Activity> clazz) {
		Logger.d(getClass(), "Launch activity " + clazz);
		Intent i = new Intent(this, clazz);
		startActivity(i);
	}

	public Activity getRootActivity() {
		Activity root = this;
		while (root.getParent() != null) {
			root = root.getParent();
		}
		return root;
	}

	/**
	 * Called when a view has been clicked.<br>
	 * Override it for handling OnClickEvent
	 * 
	 * @param v - source event
	 */
	protected void handleClick(View v) {
	}

	private class ClickListener implements OnClickListener {

		public void onClick(View v) {
			if (v instanceof TextView) {
				Logger.d(getClass(), ((TextView) v).getText() + " clicked");
			}
			handleClick(v);
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK)) {
			finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void finish() {
		if (doFinish()) {
			if (getParent() instanceof GroupBaseActivity) {
				((GroupBaseActivity) getParent()).goBack();
			} else {
				super.finish();
			}
		}
	}

	protected boolean doFinish() {
		return true;
	}

	/**
	 * @return the applicationSettings
	 */
	public final AppConfig getConfig() {
		if (conf == null) {
			conf = ((LifeBacklogApp) getApplication()).getConfig();
		}
		return conf;
	}

	public final void setActivityResult(int resultCode) {
		setActivityResult(resultCode, null);
	}

	public final void setActivityResult(int resultCode, Intent resultData) {
		synchronized (this) {
			getIntent().putExtra(RESULT_CODE, resultCode);
			getIntent().putExtra(RESULT_DATA, resultData);
		}
	}

	protected void notifyLocaleChanged() {
		sendBroadcast(new LocaleChangedEvent());
	}

}
